library(shiny)
library(shinyAce)

modes <- getAceModes()
themes <- getAceThemes()

init <- "createData <- function(rows) {
  data.frame(col1 = 1:rows, col2 = rnorm(rows))
}"

# define UI for application that demonstrates a simple Ace editor
ui <- shinyUI(
  pageWithSidebar(
    headerPanel("Simple Shiny Ace!"),
    sidebarPanel(
      selectInput("mode", "Mode: ", choices = modes, selected = "r"),
      selectInput("theme", "Theme: ", choices = themes, selected = "ambience"),
      numericInput("size", "Tab size:", 4),
      radioButtons("soft", NULL, c("Soft tabs" = TRUE, "Hard tabs" = FALSE), inline = TRUE),
      radioButtons("invisible", NULL, c("Hide invisibles" = FALSE, "Show invisibles" = TRUE), inline = TRUE),
      actionButton("reset", "Reset text"),
      actionButton("clear", "Clear text"),
      HTML("<hr />"),
      helpText(HTML("A simple Shiny Ace editor.
                  <p>Created using <a href = \"http://github.com/trestletech/shinyAce\">shinyAce</a>."))
    ),
    mainPanel(
      aceEditor(
        outputId = "ace",
        # to access content of `selectionId` in server.R use `ace_selection`
        # i.e., the outputId is prepended to the selectionId for use
        # with Shiny modules
        selectionId = "selection",
        value = init,
        placeholder = "Show a placeholder when the editor is empty ..."
      )
    )
  )
)


# define server logic required to generate simple ace editor
server <- shinyServer(function(input, output, session) {
  observe({
    # print all editor content to the R console
    cat(input$ace, "\n")
  })
  
  observe({
    # print only selected editor content to the R console
    # to access content of `selectionId` use `ace_selection`
    # i.e., the outputId is prepended to the selectionId for
    # use with Shiny modules
    cat(input$ace_selection, "\n")
  })
  
  observe({
    updateAceEditor(
      session,
      "ace",
      theme = input$theme,
      mode = input$mode,
      tabSize = input$size,
      useSoftTabs = as.logical(input$soft),
      showInvisibles = as.logical(input$invisible)
    )
  })
  
  observeEvent(input$reset, {
    updateAceEditor(session, "ace", value = init)
  })
  
  observeEvent(input$clear, {
    updateAceEditor(session, "ace", value = "")
  })
})

shinyApp(ui, server)
# the end 


